<?php
	/**
	 *
	 *  生成缓存的类
	 *
	 * eg:
	 * $cache = new makeCache();
	 * //生成缓存文件
	 * $cache -> makeCacheFile('content','config_cache');
	 * //读取缓存文件
	 * include $makeCache->getCacheFilePath('config');
	 * print_r($config_cache);
	 *
	 * */

	class makeCache{

		private $cacheDir,$content;
		public $cacheFilePath,$cacheContent,$handle;

		//获取缓存路径
		public function getCacheFilePath($cacheName,$cacheDir='./cache/',$ext='.php'){
			return $this->cacheFilePath = $cacheDir.$cacheName.$ext;
		}

		//生成缓存文件
		public function makeCacheFile($cacheName,$cacheDir='./cache/',$ext='.php'){
            global $DB;
            //判断文件最后修改时间
			if($this->getFileModifyTime($cacheName)){
				switch ($cacheName){
					case 'config':
						$sql = 'SELECT * FROM index_config LIMIT 0,1';
						$configArray = $DB->fetch_array($DB->getquery($sql));
						$this->content = "<?php\n\t\$config_cache = array(
							'sitename'  => '{$configArray['sitename']}',
							'keywords'  => '{$configArray['keywords']}',
							'icp'       => '{$configArray['icp']}',
							'cur_tplDir'=> '{$configArray['cur_tplDir']}',
							'water_mark'=> '{$configArray['water_mark']}'
						); \n?>";
						break;
				}
				$this->getCacheFilePath($cacheName);
				$this->handle = @fopen($this->cacheFilePath,'wb');
				@fwrite($this->handle,$this->content);
				@fclose($this->handle);
			}
		}

		//判断文件修改时间 是否需要重新生成缓存
		private function getFileModifyTime($cacheName,$cacheDir='./cache/',$ext='.php'){
			$filemtime = date(@filemtime($cacheDir.$cacheName.$ext));
			if(file_exists($cacheDir.$cacheName.$ext)){
				if($filemtime+3600<time()){
					return true;
				}else{
					return false;
				}
			}
			else{
				return true;
			}
		}

		//删除缓存文件并且重新生成缓存
		public function unlinkCacheFile($cacheName,$cacheDir='./cache/',$ext='.php'){
            $files = scandir($cacheDir);
            if(is_dir($cacheDir)){
              foreach($files as $value){
                 if(file_exists($cacheDir.$value.$ext)){
                      unlink($cacheDir.$cacheName.$ext);
                   }
                }
            }
            //生成缓存
			$this->makeCacheFile($cacheName);
		}
	}
?>